package com.mdnote.structure.stack;

import javax.swing.*;
import java.util.Scanner;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/8/23 23:26
 * @description 使用数组构造栈
 */
public class ArrayStack {

    // 数据
    private int[] data;

    // 指针
    private int top;

    // 最大大小
    private int maxSize;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        // top指向栈顶元素
        this.top = -1;
        this.data = new int[maxSize];
    }

    // 是否为空
    public boolean isEmpty() {
        return top == -1;
    }

    // 是否为满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    // 入栈
    public void push(int value) {
        if (isFull()) {
            throw new RuntimeException("the stack is full");
        }
        this.data[++top] = value;
    }

    // 出战
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("the stack is empty");
        }
        return this.data[top--];
    }


    // 看一眼栈顶元素
    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("the stack is empty");
        }
        return this.data[top];
    }

    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(5);

        Scanner scanner = new Scanner(System.in);

        OUTER:
        while (true) {
            System.out.println("please enter your operation:");
            System.out.println("[A] push");
            System.out.println("[B] pop");
            System.out.println("[C] peek");
            System.out.println("[D] exit");
            System.out.println("----------------------");

            char operationFlagChar = scanner.next().charAt(0);
            switch (operationFlagChar) {
                case 'A':
                    try {
                        arrayStack.push(scanner.nextInt());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'B':
                    try {
                        System.out.println(arrayStack.pop());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'C':
                    try {
                        System.out.println(arrayStack.peek());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'D':
                    break OUTER;
            }

        }

    }


}
